package com.dayu.web.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.dayu.finecomm.pojo.DeviceConfig;
import com.dayu.finecomm.pojo.DevicePusher;
import com.dayu.web.param.DeviceId;
import com.dayu.web.param.DeviceParam;
import com.dayu.web.utils.YamlUtil;
import com.dayu.web.vo.DeviceState;

/**
 * 网关service
 * 
 * @author Chenjiawei
 *
 *         2017年6月12日
 */
@Service
public class DeviceService {

	/**
	 * 获取网关运行状态
	 */
	public List<DeviceState> getDevicesState() {

		List<DeviceConfig> list = YamlUtil.getDeviceConfig();

		List<DeviceState> ll = new ArrayList<DeviceState>();
		for (DeviceConfig d : list) {

			DeviceState ds = new DeviceState();
			ds.enable = d.enabled;
			ds.name = d.name;
			ds.port = d.port;
			ds.state = d.enabled;

			ll.add(ds);
		}
		return ll;
	}

	/**
	 * 新增网关
	 */
	public List<DeviceConfig> addDevice(DeviceParam device) {
		List<DeviceConfig> list = YamlUtil.getDeviceConfig();

		if (list.size() > 0) {
			DeviceConfig deviceConfig = toDevice(device, list.get(0).pushers);
			list.add(deviceConfig);
		} else {
			list.add(updateDevice(new DeviceConfig(), device));
		}

		return list;

	}

	public DeviceConfig toDevice(DeviceParam param, List<DevicePusher> pushers) {

		DeviceConfig dc = new DeviceConfig();
		dc.enabled = param.enable;
		dc.name = param.name;
		dc.prefix = param.prefix;
		dc.host = param.host;
		dc.port = param.port;
		dc.type = param.type;
		dc.protocols = param.protocols;
		dc.pushers = pushers;

		return dc;
	}

	/**
	 * 更新单个网关
	 */
	public DeviceConfig updateDevice(DeviceConfig src, DeviceParam param) {

		src.enabled = param.enable;
		src.name = param.name;
		src.prefix = param.prefix;
		src.host = param.host;
		src.port = param.port;
		src.type = param.type;
		src.protocols = param.protocols;

		return src;
	}

	/**
	 * 修改网关
	 */
	public List<DeviceConfig> updateDevices(DeviceParam deviceParam) {
		List<DeviceConfig> list = YamlUtil.getDeviceConfig();

		DeviceConfig deviceConfig = null;

		for (DeviceConfig dc : list) {

			if (dc.name.equals(deviceParam.srcName)) {
				deviceConfig = dc;
				break;
			}
		}

		if (deviceConfig != null) {
			list.remove(deviceConfig);

			list.add(updateDevice(deviceConfig, deviceParam));
		}

		return list;
	}

	/**
	 * 删除网关
	 */
	public List<DeviceConfig> delDevice(DeviceId deviceId) {

		List<DeviceConfig> list = YamlUtil.getDeviceConfig();

		DeviceConfig deviceConfig = null;

		for (DeviceConfig dc : list) {

			if (dc.name.equals(deviceId.srcName)) {
				deviceConfig = dc;
				break;
			}
		}

		if (deviceConfig != null) {
			list.remove(deviceConfig);
		}
		return list;
	}

}
